import nodemailer from 'nodemailer';
import getconfigyaml from '../model/cfg.js';

export class SMTP extends plugin {
    constructor(e) {
        super({
            name: "[MEMZ-Plugin]发送邮件",
            dsc: "发送邮件",
            event: "message",
            priority: 500,
            rule: [
                {
                    reg: "^#发邮件(.+)$", // 使用分号分割变量，格式为#发邮件收件人;发件人姓名;邮件主题;邮件内容
                    fnc: "youjian",
                },
            ],
        });
        this.e = e;
    }

    async youjian(messageObj) {
        const config = getconfigyaml()
        const SMTPUser = config.SMTPUser
        const SMTPPass = config.SMTPPass
        const SMTPPort = config.SMTPPort
        const SMTPURL = config.SMTPURL
        
        try {
            // 提取文本消息
            const message = messageObj.raw_message;
            console.log("消息内容:", message);

            const matchResult = message.match(/^#发邮件(.+);(.+);(.+);(.+)$/);
            if (!matchResult) {
                // 修改错误消息的回复方式
                this.reply([messageObj, "错误：消息格式不正确."]);
                return;
            }

            const [, to, fromName, subject, content] = matchResult;
            // 读取 SMTP 配置文件
            
            const transporter = nodemailer.createTransport({
                host: SMTPURL,
                port: SMTPPort,
                secure: true,
                auth: {
                    user: SMTPUser,
                    pass: SMTPPass
                }
            });

                
            // 发送邮件
            const info = await transporter.sendMail({
                from: `"${fromName}" <${SMTPUser}>`,
                to,
                subject,
                text: content,
                html: `<h1>${content}</h1>`
            });

            this.reply(["消息已发送:", info.messageId]);
        } catch (error) {
            this.reply(["发送电子邮件时出错:", error]);
        }
}
}
